import { computed } from "vue";
import { RouteRecordRaw, useRoute, useRouter } from "vue-router";
import { homeRoutes } from '@/router';
import { MenuType } from "@/components";

const dropList: MenuType[] = [];

function transferToMenu(params: RouteRecordRaw[] = [], parent = '') {
    const menuList: MenuType[] = [];
    params.forEach(item => {
        const
            tmp = item.path.includes('/') ? item.path : `${parent}/${item.path}`,
            path = tmp.replace(/[//]/g, '/'),
            menu: MenuType = { index: path, name: item.name as string, meta: { title: item.name, ...item.meta } };
        // 存在子菜单时，是一个SubMenu，将meta上的一些信息传递过去
        if (item.children?.length) {
            menu.children = transferToMenu(item.children, path);
            menu.subMenuProps = {
                index: path,
                disabled: item.meta?.disabled ? true : false
            }
        } else {
            menu.menuItemProps = {
                index: path,
                disabled: item.meta?.disabled ? true : false
            }
            dropList.push(menu);
        }
        menuList.push(menu)
    })
    return menuList;
}

function useMenus() {
    dropList.splice(0);
    const menus = transferToMenu(homeRoutes);

    // 菜单点击事件
    const router = useRouter();
    const onMenuItemClick = (handle: Event | null, data: MenuType) => {
        // console.log('router', handle, data)
        // router.push({ name: data.name });
        router.push({ path: data.index });
    };

    const route = useRoute();
    const defaultMenu = computed(() => route.path)

    return {
        defaultMenu,
        menus,
        dropList,
        onMenuItemClick
    }
}
export { useMenus }